var app = getApp();
var https = "https://www.moreclub.cn/";
var htp = 'http://more-image.oss-cn-beijing.aliyuncs.com/pinzuominiapp/';
var http = 'http://10.150.7.245:8005/';
var http1 = 'http://10.150.7.248:8001/'
var http2 = 'http://59.110.53.149:8088/'
var util = require('../../utils/util.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')
var qqmapsdk = new QQMapWX({
  key: 'WYUBZ-QQ6C5-KL5IO-QCQQX-VA4XV-YVFPK'
});

var showbox;
var city;
var cityId;
var chcity

var page = 0;
var ps;
let col1H = 0;
let col2H = 0;
let fabuH = 0;
let imageObj1 = []
let imageObj2 = []
let isto = false
let isout = false

var getList = function list(that) {
  //var datalist = wx.getStorageSync('datalist');
  //签到人数显示
  //var page = 0 
  
  wx.request({
    url: https + 'v3/signin/open/morespace/'+chcity,
    //url: https + 'v3/signin/open/morespace/cd',
    data: {
      pn: page,
      ps: ps
    },
    //dataType: "application/json",
    success: function (res) {
     console.log(res)
      if (res.data.success) {
        var judata = res.data.data
        if(page==0){
          let interObj = {}

            interObj.sininCount = judata.sininCount,//全城约酒人数
            interObj.nickName1 = judata.sininMoreSpace.signInteractionDto.nickName,
            interObj.userThumb = judata.sininMoreSpace.signInteractionDto.userThumb,
            interObj.content = judata.sininMoreSpace.signInteractionDto.content,
            interObj.preCount = judata.preCount,//全城动态人数
            interObj.fromThumb = judata.prefeerDto.fromThumb,
            interObj.nickName2 = judata.prefeerDto.nickName,
            interObj.prefeerContent = judata.prefeerDto.prefeerContent



          that.setData({
            interObj: interObj
          })
        }
        

        if (judata != null) {
          var datalist = res.data.data.sininMoreSpaces;
          //console.log(datalist)

          // try {
          //   wx.setStorageSync('datalist', datalist);
          //   wx.setStorageSync('judata', judata);
          // } catch (e) {
          // }

          let personArr = []
          //let personArr = that.data.personArr

          for (var i = 0; i < datalist.length; i++) {

            var p = datalist[i].userAvatar;
            var name = datalist[i].userName;
            // var day = datalist[i].day;
            var age = datalist[i].age;
            var gender = datalist[i].gender;
            var merchantName = datalist[i].merchantName;
            var mid = datalist[i].mid;
            var uid1 = datalist[i].uid;
            var signinTime = datalist[i].signinTime;
            var signInteractionDto = datalist[i].signInteractionDto;
            if (signInteractionDto != null) {
              var type1 = datalist[i].signInteractionDto.type;
              if (type1 == 5 || type1 == null) {
                var txt = 0;
              }
              if (type1 == 3) {
                var txt = 1;
              }
              if (type1 == 6) {
                var txt = 2;
              }
              if (type1 == 4) {
                var txt = 3;
              }
              if (type1 == 1) {
                var txt = 4;
              }
              if (type1 == 2) {
                var txt = 5;
              }
              var cont = datalist[i].signInteractionDto.content;
              var gift = datalist[i].signInteractionDto.gift;
              var sid = datalist[i].signInteractionDto.sid;
            }

            var oDate = new Date().getTime();
            var nTime = Math.abs(oDate - signinTime);
            var day1 = Math.floor(nTime / 86400000);
            var hour = Math.floor(nTime % 86400000 / 3600000);
            var minute = Math.floor(nTime % 86400000 % 3600000 / 60000);
            var day;
   
            if (hour >=1&&hour<24) {
              var day = hour + '小时' 
            }
            if (day1 <= 0 && hour < 1 && minute>=1){
              var day = minute +'分钟'
            }
            if(minute<1&&day1<1&&hour<1){
              var day = '刚刚'
            }
            if(day1>0){
              var day = day1+'天'
            }

           

            let obj = {}
            obj.height = 0,
              obj.pic = p || null,
              obj.name = name,
              obj.age = age,
              obj.day = day,
              obj.uid1 = uid1,
              obj.gender = gender,
              obj.mid = mid,
              obj.gift = gift,
              obj.txt = txt,
              obj.sid = sid,
              obj.content = cont,
              obj.merchantName = merchantName,
              obj.timestamp = signinTime,
              obj.height = 186,
              obj.signInteractionDto = signInteractionDto
            personArr.push(obj)
            //images1.push(obj)
          }
          
          // if (images != null) {
          //   //that.data.totallist.concat(images);

          //   var oldlist = that.data.totallist;
          //   for (var i = 0; i < images.length; i++) {
          //     oldlist.push(images[i])
          //   }
          // }

          let img1 = {}
          let img2 = {}
          //let baseId = "img-" + (+new Date());
          let col1 = that.data.col1;
          let col2 = that.data.col2;
          let height = 0;
          for (let i = 0; i < personArr.length; i++) {

            if (i % 2 == 0) {

              img1 = personArr[i]
              col1H += 186
              col1.push(img1)
              //console.log(imageObj1)
            } else {

              img2 = personArr[i]
              col2H += 186
              // img2.pop()
              col2.push(img2)

            }


          }


          try {
            wx.setStorageSync('col1', col1);
            wx.setStorageSync('col2', col2);
          } catch (e) {
          }

          that.setData({
            personArr: personArr,
            col1: col1,
            col2: col2
          })
       

        }
      }

    },
    fail:function(res){
      console.log(res)
      var errMsg = res.errMsg
      if (errMsg){
        wx.showToast({
          title: '网络请求超时，请稍后重试',
          duration: 1000
        })
      }
      
    }
  })
   
}

Page({
  data: {
    src: [htp + 'pinzuo_bg_6_o.png', htp + 'pinzuo_bg_4_y.png', htp + 'pinzuo_bg_3_r.png', htp + 'pinzuo_bg_2_p.png', htp + 'pinzuo_bg_1_g.png', htp + 'pinzuo_bg_5_b.png'],
    colors: ['#f8a52c', '#f6e33e', '#ef4444', '#8c32d6', '#23c114', '#08cee1'],
    icon: ['pinzuo_6_pgz_color@2x.png', 'pinzuo_4_llt_color@2x.png', 'pinzuo_3_wyx_color@2x.png', 'pinzuo_2_qhd_color@2x.png', 'pinzuo_1_bgm_color@2x.png', 'pinzuo_5_bsh_color@2x.png'],
    icon2: ['buyuadrink_white@2x.png', 'cocktail_white@2x.png', 'beerbrew_white@2x.png', 'wine_white@2x.png', 'whiskey_white@2x.png', 'importbeer_white@2x.png', 'champagne_white@2x.png', 'brandy_white@2x.png', 'saki_white@2x.png'],
    tent: ['拼个座', '聊撩天', '玩游戏', '求回答', '帮个忙', '憋说话'],
    logoPosition:false,
    scrollH: 0,
    imgWidth: 0,
    loadingCount: 0,
    //images: [],
    col1: [],
    col2: [],
    totallist: [],
   
    hiddenLoading: true,
  },

  onShow:function(){
    var that = this
    // wx.getStorage({
    //   key: 'city',
    //   success: function (res) {
    //     console.log(res.data)
    //   }
    // })

   
    
    var personArr = wx.getStorageSync('personArr') || [];  
    if(isout){
      that.setData({
        hiddenLoading: false
      })
      isout = false
    }
  

    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        console.log(res)
        var networkType = res.networkType
        if (networkType=='none'){
          wx.showToast({
            title: '无网络，请确认连接后重试',
            duration: 1000
          })
        }
      }
    })
    
   
      
    wx.getSystemInfo({
      success: (res) => {
        let ww = res.windowWidth;
        let wh = res.windowHeight;
        let imgWidth = ww * 0.48;
        let scrollH = wh;
        console.log(scrollH)


        this.setData({
          scrollH: scrollH,
          imgWidth: imgWidth,
          w: ww,
          wh: wh
        });
       
      
      }
    })

    console.log(personArr)
    for (var i = 0; i < personArr.length; i++) {
      if (personArr[i].isShow) {
        that.setData({
          showbox: true
        })
      } else {
        that.setData({
          showbox: false
        })
      }
    }

    var falg = false
    wx.getStorage({
      key: 'chatMsg1',
      success: function (res) {
        console.log(res.data)

        if (res.data.data && !falg) {
          that.setData({
            showbox: true
          })

        }
      }
    })
    falg = true
   
  },

  onUnload:function(){
    isout = true

  },
  // onHide: function () {
  //   isto = true
  // },
 


  //刷新处理
  onPullDownRefresh() {
    　　console.log('--------下拉刷新-------')
    　　wx.showNavigationBarLoading() //在标题栏中显示加载

    　　wx.request({
      url: '',
      data: {},
      method: 'GET',
      // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    })               
  },

 

  onLoad: function (options) {
    var that = this;
    var access_token = wx.getStorageSync('inToken');
    wx.setNavigationBarTitle({//设置标题
      title: "More摩儿-在酒吧发现有趣朋友"
    });

   
   
  },
  onReady:function(){
    var that = this
    //city = wx.getStorageSync('city')
    qqmapsdk.reverseGeocoder({

      success: function (res) {
        console.log(res)

        var address = res.result.ad_info;
        var usercity = address.city;
        var lat1 = address.location.lat;
        var lng1 = address.location.lng;
        console.log(usercity)

        if (address.city == '成都市') {
          chcity = "cd";
          cityId = "2"
        } else if (address.city == '北京市') {
          chcity = "bj";
          cityId = "1"
        } else if (address.city == '昆明市') {
          chcity = "km";
          cityId = "5"
        } else if (address.city == '上海市') {
          chcity = "sh";
          cityId = "3"
        }


        try {
          wx.setStorageSync('city', chcity);
          wx.setStorageSync('cityId', cityId);
          wx.setStorageSync('usercity', usercity);

        } catch (e) {
        }

      },
      fail: function (res) {
        chcity = 'cd'
        try {
          wx.setStorageSync('city', 'cd');
          wx.setStorageSync('cityId', 2);
          wx.setStorageSync('lat1', '');
          wx.setStorageSync('lng1', '');
          wx.setStorageSync('usercity', '成都');

        } catch (e) {
        }

        // wx.showToast({
        //   title: '定位失败',
        //   duration: 1000
        // })
      },
      complete: function (res) {

        try {
          wx.setStorageSync('lat1', lat1);
          wx.setStorageSync('lng1', lng1);

        } catch (e) {
        }
      }
    });

    // if(!chcity||chcity==''){
    //   chcity =='cd'
    // }
    if (typeof (chcity) == "undefined" && chcity == null){
      chcity = 'cd'
    }
    page = 0;
    ps = 8;
    getList(that);
    console.log('city', chcity)
    // setTimeout(function () {
     
    // }, 2000)
   
    that.setData({
      hiddenLoading: true
    })
  },
//遮罩层
  openOpcaty:function(){
      var that = this;
      that.setData({
        isOpacity:true
      })
  },
  colse:function(){
    var that = this;
    that.setData({
      isOpacity: false
    })
  },

  //进入发布动态
  pubstate:function(){
    var that = this;
    wx.navigateTo({
      url: '../dynamics/dynamics'
    })
    that.setData({
      isOpacity: false
    })
  },
  //进入发拼座
  openInter:function(){
    var that = this;
    wx.navigateTo({
      url: '../interaction/interaction'
    })
    that.setData({
      isOpacity: false
    })
  },

  //跳转另个小程序
  tiaozhuan:function(){
    wx.navigateToMiniProgram({
      appId: 'wx3abd6a1e615ce065',
      path: '',
      extraData: {
        foo: 'bar'
      },
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },

  //提示开发中
  develop:function(){
    wx.showModal({
      title: '提示',
      content: '功能正在开发中，敬请期待',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {

        }
      }
    })
    
  },

  //进入聊天列表
  into_chatlist: function () {
    var that = this;
    // that.setData({
    //   showbox: false,
    //   isinto: true
    // })
    try {
      wx.removeStorageSync('chatMsg1')
    } catch (e) {
    }

    wx.navigateTo({
      url: '../chatlist/chatlist'
    })
    //isinto:true


    wx.setTopBarText({
      text: 'More摩儿-在酒吧发现有趣朋友'
    })

    // wx.setTopBarText({
    //   text: 'More精选酒吧'
    // })
  },
 
  //进入聊天
  into_chat: function (e) {
    var access_token = wx.getStorageSync('inToken');
    var uid = wx.getStorageSync('uid');
    var col1 = wx.getStorageSync('col1');
    var idx = e.currentTarget.dataset.idx;
    console.log(e)

    var myName = wx.getStorageSync('myUsername')

    var nameList = {}
    nameList.myName = myName,
      nameList.your = col1[idx].uid1,
      nameList.yourName = col1[idx].name,
      nameList.userAvatar = col1[idx].pic

    if (uid != col1[idx].uid1) {
      wx.navigateTo({
        url: '../chat/chat?username=' + JSON.stringify(nameList)
      })
    }

  },

  into_chat2: function (e) {
    var access_token = wx.getStorageSync('inToken');
    var uid = wx.getStorageSync('uid');
    var col2 = wx.getStorageSync('col2');
    var idy = e.currentTarget.dataset.idy;
    console.log(e)

    var myName = wx.getStorageSync('myUsername')

    var nameList = {}
    nameList.myName = myName,
      nameList.your = col2[idy].uid1,
      nameList.yourName = col2[idy].name,
      nameList.userAvatar = col2[idy].pic

    if (uid != col2[idy].uid1) {
      wx.navigateTo({
        url: '../chat/chat?username=' + JSON.stringify(nameList)
      })
    }

  },

  onReachBottom: function () {
    // 页面上拉触底事件的处理函数
    var that = this;
    
    if (that.data.col1 != null && that.data.col1.length != 0 || that.data.col2 != null && that.data.col2.length != 0) {
      
      page += 1;
      ps=8
      getList(that,chcity);
     
    }else {
      wx.showToast({
        title: '已加载完成',
        duration: 1000
      })
      
    }
  },

  onShareAppMessage: function () {
    // 用户点击右上角分享
    return {
      title: '摩儿-全城有趣的人都在这', // 分享标题
      desc: '摩儿-全城有趣的人都在这', // 分享描述

      path: '/pages/home/home'
    }
  }
})